package com.itic.mall.mobile.login;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.malltoken.persistence.model.MallToken;
import com.itic.mall.system.user.persistence.model.MallUser;


/**
 * 用户登入接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/login")
public class MallLoginInterface
     extends BaseMobileInterface {
	
	
	/**
	 * 添加手机号码，验证码的登入
	 * @return
	 */
	@RequestMapping(value="/bindYunId")
    @ResponseBody
    public Map<String,Object> bindYunId(HttpServletRequest request,HttpServletResponse response,String token,String yunId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(yunId) ){
    			//判断手机号码
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				user.setYunId(yunId);
					mallUserService.edit(user);
    				result = SUCCESS;
    				errorCode = SUCCESS_ERROR_CODE;
			    	errorMsg = SUCCESS_ERROR_MSG;
    			}
    		}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
	
	/**
	 * 添加手机号码，验证码的登入
	 * @return
	 */
	@RequestMapping(value="/phone/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String phone,String code){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		//判断必要的参数
    		if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) ){
    			//判断手机号码
    			if( isPhoneCode(phone, code) ){
    				//判断手机号码有没有
        			MallUser user = getMallUserByPhone(phone);
        			if( null != user ){
        				//生成新的TOKEN
        				MallToken createToken = null;
        				//直接生成新的TOKEN返回 用户
	    				createToken = createToken(user);
	    				
	    				String addResult = mallTokenService.add(createToken);
	    				if( SUCCESS.equals(addResult) ){
	    					result = SUCCESS;
	    	    			errorCode = SUCCESS_ERROR_CODE;
	    	            	errorMsg = SUCCESS_ERROR_MSG;
	    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	            	dataMap.put("accessToken", createToken.getAccessToken());
	    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
	    	            	dataMap.put("userId", user.getId());
	    	            	resultMap.put(DATA, dataMap);
	    	            	
	    				}
        			}else{
        				result = FAIL;
    	    			errorCode = WEIXIN_AUTH_ERROR_CODE;
    	            	errorMsg = WEIXIN_AUTH_ERROR_MSG;
        			}
    			}else{
    				result = FAIL;
	    			errorCode = PHONE_CODE_ERROR_CODE;
	            	errorMsg = PHONE_CODE_ERROR_MSG;
    			}
    		}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
	
	
	/**
	 * 添加手机号码，验证码的登入
	 * @return
	 */
	@RequestMapping(value="/isHide")
    @ResponseBody
    public Map<String,Object> isweixin(HttpServletRequest request,HttpServletResponse response){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		String isHide = sysSettingService.getByKey("IS_HIDE");//如果为1,则隐藏
    		if( StringHelper.isBlank(isHide)){
    			isHide="show";//默认不隐藏
    		}
    		resultMap.put(DATA, isHide);
    		result=SUCCESS;
    		errorCode = SUCCESS_ERROR_CODE;
        	errorMsg = SUCCESS_ERROR_MSG;
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
	
	@RequestMapping(value="/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String token,String openid,String unionId,String userHeadImg,String userNickName,String phone,String yunId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		if( StringHelper.isNotBlank(token) ){
				MallUser user4 = getMallUserByToken(token);
				if( null != user4 ){
					//云ID不是NULL 或不为空的情况下都更新yunId
    				if( !"null".equals(yunId) && StringHelper.isNotBlank(yunId) ){
    					//更新用户yunId
    					user4.setYunId(yunId);
    					mallUserService.edit(user4);
    				}
    				
					result = SUCCESS;
	    			errorCode = SUCCESS_ERROR_CODE;
	            	errorMsg = SUCCESS_ERROR_MSG;
				}
			}else{
				//判断参数里是否有unionId，或者openid 
				//如果有unionId则可以登入,而且是否在openid
				if( StringHelper.isNotBlank(unionId) ){
					//判断uniond_id本地库有没有
	    			MallUser user = mallUserService.getByUnionId(unionId);
	    			if( null != user ){
	    				//云ID不是NULL 或不为空的情况下都更新yunId
	    				if( !"null".equals(yunId) && StringHelper.isNotBlank(yunId) ){
	    					//更新用户yunId
	    					user.setYunId(yunId);
	    					mallUserService.edit(user);
	    				}
	    				
	    				if( StringHelper.isNotBlank(openid) && StringHelper.isBlank(user.getOpenid()) ){
	    					user.setOpenid(openid);
	    					mallUserService.edit(user);
	    				}
						
						MallToken createToken = null;
	    				//直接生成新的TOKEN返回 用户
	    				createToken = createToken(user);
	    				
	    				String addResult = mallTokenService.add(createToken);
	    				if( SUCCESS.equals(addResult) ){
	    					result = SUCCESS;
	    	    			errorCode = SUCCESS_ERROR_CODE;
	    	            	errorMsg = SUCCESS_ERROR_MSG;
	    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	            	dataMap.put("accessToken", createToken.getAccessToken());
	    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
	    	            	dataMap.put("userId", user.getId());
	    	            	resultMap.put(DATA, dataMap);
	    				}
	    			}else{
	    				//注册新用户，生成新的TOKEN，返回
	    				MallUser regUser = regUser(openid,unionId,userHeadImg,userNickName,phone,yunId);
	    				MallToken createToken = createToken(regUser);
	    				//String addResult = mallTokenService。addTokenAndRegUser(createToken,regUser);
	    				String addResult = mallTokenService.addTokenAndRegUser(createToken, regUser);
	    				if( SUCCESS.equals(addResult) ){
	    					result = SUCCESS;
	    	    			errorCode = SUCCESS_ERROR_CODE;
	    	            	errorMsg = SUCCESS_ERROR_MSG;
	    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	            	dataMap.put("accessToken", createToken.getAccessToken());
	    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
	    	            	dataMap.put("userId", regUser.getId());
	    	            	resultMap.put(DATA, dataMap);
	    				}
	    				
	    			}
				}
			}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
	
	
	/**
	 * 登入方式改1token登入，2.unionId登入.3手机号码登入
	 * @param request
	 * @param response
	 * @param token
	 * @param openid
	 * @param unionId
	 * @param userHeadImg
	 * @param userNickName
	 * @param phone
	 * @param code
	 * @return
	
	@RequestMapping(value="/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String token,String openid,String unionId,String userHeadImg,String userNickName,String phone,String yunId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		if( StringHelper.isNotBlank(token) ){
				MallUser user4 = getMallUserByToken(token);
				if( null != user4 ){
					result = SUCCESS;
	    			errorCode = SUCCESS_ERROR_CODE;
	            	errorMsg = SUCCESS_ERROR_MSG;
				}
			}else{
				if( StringHelper.isNotBlank(unionId) ){
	    			//判断uniond_id本地库有没有
	    			MallUser user = mallUserService.getByUnionId(unionId);
	    			
	    			if( null != user ){
	    				if(StringHelper.isNotBlank(user.getYunId())){
	    					MallToken createToken = null;
		    				//直接生成新的TOKEN返回 用户
		    				createToken = createToken(user);
		    				
		    				String addResult = mallTokenService.add(createToken);
		    				if( SUCCESS.equals(addResult) ){
		    					result = SUCCESS;
		    	    			errorCode = SUCCESS_ERROR_CODE;
		    	            	errorMsg = SUCCESS_ERROR_MSG;
		    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
		    	            	dataMap.put("accessToken", createToken.getAccessToken());
		    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
		    	            	dataMap.put("userId", user.getId());
		    	            	resultMap.put(DATA, dataMap);
		    				}
	    				}else{
	    					if( StringHelper.isNotBlank(yunId) ){
	    						user.setYunId(yunId);
	    						mallUserService.edit(user);
	    						MallToken createToken = null;
			    				//直接生成新的TOKEN返回 用户
			    				createToken = createToken(user);
			    				
			    				String addResult = mallTokenService.add(createToken);
			    				if( SUCCESS.equals(addResult) ){
			    					result = SUCCESS;
			    	    			errorCode = SUCCESS_ERROR_CODE;
			    	            	errorMsg = SUCCESS_ERROR_MSG;
			    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
			    	            	dataMap.put("accessToken", createToken.getAccessToken());
			    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
			    	            	dataMap.put("userId", user.getId());
			    	            	resultMap.put(DATA, dataMap);
			    				}
	    					}else{
	    						MallToken createToken = null;
			    				//直接生成新的TOKEN返回 用户
			    				createToken = createToken(user);
			    				
			    				String addResult = mallTokenService.add(createToken);
			    				if( SUCCESS.equals(addResult) ){
			    					result = SUCCESS;
			    	    			errorCode = SUCCESS_ERROR_CODE;
			    	            	errorMsg = SUCCESS_ERROR_MSG;
			    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
			    	            	dataMap.put("accessToken", createToken.getAccessToken());
			    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
			    	            	dataMap.put("userId", user.getId());
			    	            	resultMap.put(DATA, dataMap);
			    				}
	    					}
	    				}
	    				
	    			}else{
	    				//注册新用户，生成新的TOKEN，返回
	    				MallUser regUser = regUser(openid,unionId,userHeadImg,userNickName,phone,yunId);
	    				MallToken createToken = createToken(regUser);
	    				//String addResult = mallTokenService。addTokenAndRegUser(createToken,regUser);
	    				String addResult = mallTokenService.addTokenAndRegUser(createToken, regUser);
	    				if( SUCCESS.equals(addResult) ){
	    					result = SUCCESS;
	    	    			errorCode = SUCCESS_ERROR_CODE;
	    	            	errorMsg = SUCCESS_ERROR_MSG;
	    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
	    	            	dataMap.put("accessToken", createToken.getAccessToken());
	    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
	    	            	dataMap.put("userId", regUser.getId());
	    	            	resultMap.put(DATA, dataMap);
	    				}
	    				
	    			}
	    		}
			}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
	 */
	
	public MallUser regUser( String phone ){
		MallUser user = new MallUser();
    	//六个必须字段
    	user.setId(IdGen.uuid());
    	user.setIsEffective(DBConst.TRUE);
    	user.setCreateTime(new Date());
    	user.setUpdateTime(new Date());
    	user.setOrgCode(ORG_CODE);
    	user.setCreateUser(CREATE_USER);
    	//三个业务字段
    	user.setUserPhone(phone);
    	//user.setUnionId(unionId);
    	//user.setOpenid(openid);
    	//user.setUserHeadImg(userHeadImg);
    	//user.setUserNickName(userNickName);
    	user.setMoney("0");
    	
    	return user;
	}
   
    /**
     * APP用户授权登入
     * @return
    
    @RequestMapping(value="/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response,String token,String openid,String unionId,String userHeadImg,String userNickName,String phone,String code){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(userNickName) ){
    			MallUser usr = null;
    			//判断uniond_id本地库有没有
    			MallUser user1 = mallUserService.getByUnionId(unionId);
    			MallUser user2 = mallUserService.getByOpenid(openid);
    			MallUser user = mallUserService.getByName(userNickName);
    			
    			if( user != null ){
    				usr = user;
    			}
    			if( user1 != null ){
    				usr = user1;
    			}
    			if( user2 != null ){
    				usr = user2;
    			}
    			
    			if( null != usr ){
    				MallToken createToken = null;
    				//直接生成新的TOKEN返回 用户
    				createToken = createToken(usr);
    				
    				String addResult = mallTokenService.add(createToken);
    				if( SUCCESS.equals(addResult) ){
    					result = SUCCESS;
    	    			errorCode = SUCCESS_ERROR_CODE;
    	            	errorMsg = SUCCESS_ERROR_MSG;
    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
    	            	dataMap.put("accessToken", createToken.getAccessToken());
    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
    	            	dataMap.put("userId", usr.getId());
    	            	resultMap.put(DATA, dataMap);
    				}
    			}else{
    				//注册新用户，生成新的TOKEN，返回
    				MallUser regUser = regUser(openid,unionId,userHeadImg,userNickName);
    				MallToken createToken = createToken(regUser);
    				//String addResult = mallTokenService。addTokenAndRegUser(createToken,regUser);
    				String addResult = mallTokenService.addTokenAndRegUser(createToken, regUser);
    				if( SUCCESS.equals(addResult) ){
    					result = SUCCESS;
    	    			errorCode = SUCCESS_ERROR_CODE;
    	            	errorMsg = SUCCESS_ERROR_MSG;
    	            	Map<String, Object> dataMap = new HashMap<String,Object>();
    	            	dataMap.put("accessToken", createToken.getAccessToken());
    	            	dataMap.put("expiredTime", createToken.getExpiredTime());
    	            	dataMap.put("userId", regUser.getId());
    	            	resultMap.put(DATA, dataMap);
    				}
    				
    			}
    			
    			if( StringHelper.isNotBlank(token) ){
    				MallUser user4 = getMallUserByToken(token);
    				if( null != user4 ){
    					result = SUCCESS;
    	    			errorCode = SUCCESS_ERROR_CODE;
    	            	errorMsg = SUCCESS_ERROR_MSG;
    				}
    			}
    			
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "in", e.toString(),"商城登入接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } */
    
    
    /**
     * APP用户登出
     * @return
     */
    @RequestMapping(value="/out")
    @ResponseBody
    public Map<String,Object> out( HttpServletRequest request,HttpServletResponse response, String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) ){
    			MallToken selectToken = mallTokenService.getMallTokenByToken(token);
    			if( null != selectToken ){
    				result = mallTokenService.delete(selectToken);
    			}else{
    				result = SUCCESS;
    			}
    			errorCode = SUCCESS_ERROR_CODE;
            	errorMsg = SUCCESS_ERROR_MSG;
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "out", e.toString(),"商城登出接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * updateYunId
     * @return
     */
    @RequestMapping(value="/updateYunId")
    @ResponseBody
    public Map<String,Object> updateYunId( HttpServletRequest request,HttpServletResponse response, String token, String yunId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(yunId) && !"null".equals(yunId) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				//云ID不是NULL 或不为空的情况下都更新yunId
    				//更新用户yunId
					user.setYunId(yunId);
					mallUserService.edit(user);
					result = SUCCESS;
	    			errorCode = SUCCESS_ERROR_CODE;
	            	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallLoginInterface", "out", e.toString(),"商城登出接口",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }

	/**
     * 注册新用户
     * @return
     */
    public MallUser regUser( String openid,String unionId,String userHeadImg,String userNickName,String phone,String yunId ){
    	MallUser user = new MallUser();
    	//六个必须字段
    	user.setId(IdGen.uuid());
    	user.setIsEffective(DBConst.TRUE);
    	user.setCreateTime(new Date());
    	user.setUpdateTime(new Date());
    	user.setOrgCode(ORG_CODE);
    	user.setCreateUser(CREATE_USER);
    	//三个业务字段
    	user.setUnionId(unionId);
    	user.setOpenid(openid);
    	user.setUserHeadImg(userHeadImg);
    	user.setUserNickName(filterEmoji(userNickName));
    	user.setMoney("0");
    	user.setUserPhone(phone);
    	user.setYunId(yunId);
    	return user;
    }
    
    /**
     * 根据用户生成一个新的TOKEN
     * @param user
     * @return
     */
    public MallToken createToken( MallUser user ){
    	Date date = new Date();
    	//六个必须字段
    	MallToken token = new MallToken();
    	token.setId(IdGen.uuid());
    	token.setIsEffective(DBConst.TRUE);
    	token.setCreateTime(date);
    	token.setUpdateTime(date);
    	token.setOrgCode(ORG_CODE);
    	token.setCreateUser(CREATE_USER);
    	//关联字段
    	token.setUserId(user.getId());//关联用户ID
    	//三个业务字段
    	token.setType("0");//0代表友惠家商城TOKEN
    	String unionId = "";
    	if( StringHelper.isNotBlank(user.getUnionId()) ){
    		unionId = user.getUnionId();
    	}
    	String openid = "";
    	if( StringHelper.isNotBlank(user.getOpenid()) ){
    		openid = user.getOpenid();
    	}
    	
    	
    	token.setUnionId(unionId);//微信统一 ID
    	token.setOpenid(openid);//微信公众号ID
    	token.setAccessToken(getToken());//设置TOKEN
    	token.setExpiredTime(getExpiredTimeToken(date));//设置有效期
    	
    	return token;
    }
    
    
}